package com.mashibing.juc.c_020_Interview;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * volatile尽量修饰简单值（基本数据类型）
 * volatile能不用则不用
 * @author: Yuanzt
 * @Date: 2021/3/29
 */
public class T02_WithVolatile {
    //添加volatile，使Thread-2能够得到通知
    //volatile List list = new ArrayList();
    //保证线程同步，并且使Thread-2能够得到通知
    volatile List list = Collections.synchronizedList(new LinkedList<>());
    public void add(Object o) {
        list.add(o);
    }

    public int size(){
        return list.size();
    }

    public static void main(String[] args) {
        T02_WithVolatile t = new T02_WithVolatile();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                t.add(new Object());
                System.out.println("add " + i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"thread-1").start();

        new Thread(()->{
            while (true){
                if (t.size() == 5) break;
            }
            System.out.println("thread-2 结束");
        },"thread-2").start();
    }

}
